package com.qianfeng;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONObject;


@WebServlet("/upload")
public class ImgUpload extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		
		
		try {
			List<FileItem> list = fileUpload.parseRequest(req);
			
			List<String> names = new ArrayList<String>();
			for (FileItem fileItem : list) {
				String prefix = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
				
				String newName = String.valueOf(System.currentTimeMillis()).concat(UUID.randomUUID().toString()).concat(prefix);
				
				InputStream is = fileItem.getInputStream();

				FileOutputStream fos = new FileOutputStream("d:\\imgs\\"+newName);
				
				byte[] bs = new byte[1024];
				int len; 
				while((len=is.read(bs))!=-1) {
					fos.write(bs, 0, len);
				}
				fos.close();
				
				
				names.add("http://localhost:8090/imgServer/getImg?fileName="+newName); //将生成的文件名返回给客户端
			}
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("data", names);
			map.put("errno", 0);
			
			String json = JSONObject.toJSONString(map);
			
			resp.setHeader("Access-Control-Allow-Origin", "*");
			
			resp.getOutputStream().write(json.getBytes());
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Request-Method", "post");
		
		resp.setHeader("Access-Control-Max-Age", "1728000");
		
	}
	
	

}
